from django.utils import timezone
import os
import pinyin

pinyin_dict = {}
dat = os.path.join(os.path.dirname(pinyin.__file__), "Mandarin.dat")
with open(dat) as f:
    for line in f:
        k, v = line.strip().split('\t')
        pinyin_dict[k] = v.lower().split(" ")[0][:-1]


def upload_to(path, fmt='%Y-%m'):
    def closure(instance, filename):
        file_info = os.path.splitext(filename)
        ext = file_info[1]

        today = timezone.now().date()

        name = timezone.now().strftime('%Y%m%d%H%M%S') + filename[0]

        return "%s-%s/%s%s" % (path, today.strftime(fmt), name, ext.lower())

    return closure


def _pinyin_generator(chars):
    """Generate pinyin for chars, if char is not chinese character,
    itself will be returned.
    Chars must be unicode list.
    """
    for char in chars:
        key = "%X" % ord(char)
        yield pinyin_dict.get(key, '')


def get_pinyin(s, delimiter=''):
    """Return pinyin of string, the string must be unicode
    """

    return delimiter.join(_pinyin_generator(s))